package service

import (
	"context"
	"fmt"
	"iris-wms/apps/admin/web/dto/din"
	"iris-wms/apps/admin/web/dto/dout"
	"iris-wms/common/model"
	"iris-wms/common/pkg/db"
	"iris-wms/common/pkg/db/dao"

	"gorm.io/gorm"
)

var _ AdminDictService = (*adminDictService)(nil)

type AdminDictService interface {
	Create(model.AdminDict) error
	Update(model.AdminDict) error
	DeleteByIdList([]uint) error
	GetTable(din.AdminDictTableIn) ([]*dout.AdminDictOut, int64, error)
	GetList() ([]*dout.AdminDictOut, error)
	GetListByMark(string) ([]*dout.AdminDictOut, error)
}

func NewAdminDictService() *adminDictService {
	return &adminDictService{}
}

type adminDictService struct{}

func (impl *adminDictService) Create(in model.AdminDict) (err error) {
	err = db.GDB1.Create(&in).Error
	return
}

func (impl *adminDictService) Update(in model.AdminDict) (err error) {
	err = db.GDB1.Save(&in).Error
	return
}

func (impl *adminDictService) DeleteByIdList(idList []uint) (err error) {
	err = db.GDB1.Transaction(func(tx *gorm.DB) error {
		if err = tx.Delete(&model.AdminDict{}, "id in ?", idList).Error; err != nil {
			return err
		}
		return nil
	})
	return
}

func (impl *adminDictService) GetTable(in din.AdminDictTableIn) (rows []*dout.AdminDictOut, total int64, err error) {
	q := dao.Use(db.GDB1).AdminDictOut
	do := q.WithContext(context.Background())

	if in.Word != "" {
		word := fmt.Sprintf("%%%s%%", in.Word)
		do = do.Where(do.Where(q.Code.Eq(in.Word)).
			Or(q.Mark.Like(word)).
			Or(q.Label.Like(word)))
	}
	rows, total, err = do.
		Preload(q.Creator).Order(q.ID, q.Mark.Desc()).FindByPage(in.Offset(), in.PageSize)
	return
}

func (impl *adminDictService) GetList() (rows []*dout.AdminDictOut, err error) {
	q := dao.Use(db.GDB1).AdminDictOut
	do := q.WithContext(context.Background())
	rows, err = do.Order(q.ID, q.Mark.Desc()).Find()
	return
}

func (impl *adminDictService) GetListByMark(mark string) (rows []*dout.AdminDictOut, err error) {
	q := dao.Use(db.GDB1).AdminDictOut
	do := q.WithContext(context.Background())
	rows, err = do.Where(q.Mark.Eq(mark)).Find()
	return
}
